﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.TaskScheduler;


namespace FanMotionWink
{
    class ProcessUtils
    {
        public static void AutoWork()
        {
            // Store boolean flag
            bool isAdmin;
            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                WindowsPrincipal principal = new WindowsPrincipal(identity);

                // If is administrator, the variable updates from False to True
                isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }

            if (isAdmin)
            {
                return;
            }

            // re-run

            try
            {
                // 提升自己的权限
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.WorkingDirectory = Environment.CurrentDirectory;
                psi.FileName = Application.ExecutablePath;
                psi.UseShellExecute = true;
                psi.Verb = "runas";
                Process p = new Process();
                p.StartInfo = psi;
                p.Start();
                Process.GetCurrentProcess().Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show("程序无法获取Windows管理员身份运行，\n请手动使用Windows管理员身份运行");
            }
        }


        public static readonly string TaskName = @"Start WineWink - FBF7C91607156450";

        public static void ReistAsAdminAutoRunOn()
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "启动 WineWink";

                td.Principal.RunLevel = TaskRunLevel.Highest;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.Triggers.Add(new LogonTrigger { Enabled = true });
                td.Actions.Add(new ExecAction(Application.ExecutablePath, "", Environment.CurrentDirectory));
                ts.RootFolder.RegisterTaskDefinition(TaskName, td);
            }
        }

        public static void ReistAsAdminAutoRunOff()
        {
            try
            {

                using (TaskService ts = new TaskService())
                {
                    var task = ts.RootFolder.AllTasks.FirstOrDefault(item =>
                    {
                        Console.WriteLine(item.Name);
                        return item.Name == TaskName;
                    });
                    if (task != null)
                    {
                        ts.RootFolder.DeleteTask(TaskName);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

    }
}
